package org.particlethink.service.procure;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.particlethink.auth.DefaultUser;
import org.particlethink.entry.OrderStatus;
import org.particlethink.entry.PlanStatus;
import org.particlethink.entry.PlanTyp;
import org.particlethink.mapper.*;
import org.particlethink.model.*;
import org.particlethink.response.*;
import org.particlethink.utils.ListUtilsKt;
import org.particlethink.utils.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class CompanyUserImpl {//公司用户

    @Autowired
    public MasterPlanMapper masterPlanMapper;
    @Autowired
    public BatchPlanMapper batchPlanMapper;
    @Autowired
    public PlanMaterialMapper planMaterialMapper;
    @Autowired
    public OrderMapper orderMapper;
    @Autowired
    public DeliverMapper deliverMapper;
    @Autowired
    public AcceptanceMapper acceptanceMapper;
    @Autowired
    public ProjectUserMapper projectUserMapper;
    @Autowired
    public ProjectMapper projectMapper;
    @Autowired
    public MasterPlanCategoryMapper masterPlanCategoryMapper;
    @Autowired
    public CategoryMapper categoryMapper;
    @Autowired
    public MaterialMapper materialMapper;
    @Autowired
    public SupplierMapper supplierMapper;
    @Autowired
    public SupplierUserMapper supplierUserMapper;


    //查看总计划列表
    public PageInfo<MasterPlanResponse> masterPlanList(User user, String managementLevel, Integer projectId, String masterPlanNo, Integer masterPlanCategoryId, PlanStatus status, String submitUserName, Date submitStart, Date submitEnd, Integer pageNum, Integer pageSize) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 20;
        }
        List<Project> projects = null;
        if (!ObjectUtils.isEmpty(projectId)) {
            ArrayList<Integer> projectIds = new ArrayList<>();
            projectIds.add(projectId);

            projects = this.projectMapper.selectByIds(user.getToken(), projectIds);
        } else {
            projects = this.projectMapper.list(user.getToken(), "", managementLevel, user.getProjectIds());
        }


        if (projects == null || projects.isEmpty()) {
            return new PageInfo<>(Collections.emptyList());
        }
        List<ProjectUser> projectUsers;
        List<Integer> submitUserIds = null;
        if (submitUserName != null && !submitUserName.isEmpty()) {
            projectUsers = this.projectUserMapper.selectByName(submitUserName);
            submitUserIds = projectUsers.stream().map(ProjectUser::getId).collect(Collectors.toList());
            if (submitUserIds.isEmpty()) {
                return new PageInfo<>(Collections.emptyList());
            }
        } else {
            projectUsers = this.projectUserMapper.selectAll();
        }
        List<Integer> categoryIds = null;
        if (masterPlanCategoryId != null) {
            categoryIds = Collections.singletonList(masterPlanCategoryId);
        }

        PageHelper.startPage(pageNum, pageSize);
        //查找所有总计划
        PageInfo<MasterPlan> masterPlans = new PageInfo<>(this.masterPlanMapper.selectMasterPlans(masterPlanNo, projects.stream().map(Project::getId).collect(Collectors.toList()), categoryIds, status, submitUserIds, submitStart, submitEnd));

        Map<Integer, Project> projectMap = ListUtilsKt.map(projects, Project::getId);


        Map<Integer, ProjectUser> projectUserMap = ListUtilsKt.map(projectUsers, ProjectUser::getId);

        List<String> masterPlanCategoryIds = masterPlans.getList().stream().map(MasterPlan::getMasterPlanCategoryId).collect(Collectors.toList());
        List<MasterPlanCategory> masterPlanCategories = this.masterPlanCategoryMapper.selectByIds(user.getToken(), masterPlanCategoryIds);
        Map<String, MasterPlanCategory> masterPlanCategoryMap = ListUtilsKt.map(masterPlanCategories, MasterPlanCategory::getId);

        PageInfo<MasterPlanResponse> results = masterPlans.convert(masterPlan -> {
            return new MasterPlanResponse(masterPlan, projectMap.get(masterPlan.getProjectId()), masterPlanCategoryMap.get(masterPlan.getMasterPlanCategoryId()), projectUserMap.get(masterPlan.getSubmitId()), projectUserMap.get(masterPlan.getCreatorId()));
        });

        //查找所有总计划
        return results;
    }


    public List<MasterPlanExportResponse> masterPlanExport(User user, String managementLevel, Integer projectId, String masterPlanNo, Integer masterPlanCategoryId, PlanStatus status, String submitUserName, Date submitStart, Date submitEnd) {

        List<Project> projects = null;
        if (!ObjectUtils.isEmpty(projectId)) {
            ArrayList<Integer> projectIds = new ArrayList<>();
            projectIds.add(projectId);

            projects = this.projectMapper.selectByIds(user.getToken(), projectIds);
        } else {
            projects = this.projectMapper.list(user.getToken(), "", managementLevel, user.getProjectIds());
        }

        List<ProjectUser> projectUsers;
        List<Integer> submitUserIds = null;
        if (submitUserName != null && !submitUserName.isEmpty()) {
            projectUsers = this.projectUserMapper.selectByName(submitUserName);
            submitUserIds = projectUsers.stream().map(ProjectUser::getId).collect(Collectors.toList());
        } else {
            projectUsers = this.projectUserMapper.selectAll();
        }
        List<Integer> categoryIds = null;
        if (masterPlanCategoryId != null) {
            categoryIds = Collections.singletonList(masterPlanCategoryId);
        }

        //查找所有总计划
        List<MasterPlan> masterPlans = this.masterPlanMapper.selectMasterPlans(masterPlanNo, projects.stream().map(Project::getId).collect(Collectors.toList()), categoryIds, status, submitUserIds, submitStart, submitEnd);

        Map<Integer, Project> projectMap = ListUtilsKt.map(projects, Project::getId);


        Map<Integer, ProjectUser> projectUserMap = ListUtilsKt.map(projectUsers, ProjectUser::getId);

        List<String> masterPlanCategoryIds = masterPlans.stream().map(MasterPlan::getMasterPlanCategoryId).collect(Collectors.toList());
        List<MasterPlanCategory> masterPlanCategories = this.masterPlanCategoryMapper.selectByIds(user.getToken(), masterPlanCategoryIds);
        Map<String, MasterPlanCategory> masterPlanCategoryMap = ListUtilsKt.map(masterPlanCategories, MasterPlanCategory::getId);

        List<MasterPlanExportResponse> results = masterPlans.stream().map(masterPlan -> {
            return new MasterPlanExportResponse(masterPlan, projectMap.get(masterPlan.getProjectId()), masterPlanCategoryMap.get(masterPlan.getMasterPlanCategoryId()), projectUserMap.get(masterPlan.getSubmitId()));
        }).collect(Collectors.toList());

        //查找所有总计划
        return results;
    }


    //查看总计划详情
    public MasterPlanDetailResponse masterPlanDetail(int masterPlanID) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        DefaultUser defaultUser = (DefaultUser) authentication.getPrincipal();
        User user = defaultUser.getUser();
        List<BatchPlan> batchPlans = this.batchPlanMapper.selectAllByMasterPlanID(masterPlanID);
        List<Integer> projectUserIds = batchPlans.stream().flatMap(batchPlan -> Stream.of(batchPlan.getCreatorId(), batchPlan.getSubmitId())).collect(Collectors.toList());

        MasterPlan masterPlan = this.masterPlanMapper.selectByPrimaryKey(masterPlanID);
        if (masterPlan == null) {
            return null;
        }
        projectUserIds.add(masterPlan.getSubmitId());
        projectUserIds.add(masterPlan.getCreatorId());

        List<ProjectUser> projectUsers = this.projectUserMapper.selectByIds(projectUserIds.stream().distinct().collect(Collectors.toList()));
        Map<Integer, ProjectUser> projectUserMap = ListUtilsKt.map(projectUsers, ProjectUser::getId);

        List<Integer> projectIds = batchPlans.stream().map(BatchPlan::getProjectId).collect(Collectors.toList());
        projectIds.add(masterPlan.getProjectId());

        List<Project> projects = this.projectMapper.selectByIds(user.getToken(), projectIds.stream().distinct().collect(Collectors.toList()));
        Map<Integer, Project> projectMap = ListUtilsKt.map(projects, Project::getId);

        List<String> categoryIds = batchPlans.stream().map(BatchPlan::getCategoryId).collect(Collectors.toList());
        List<PlanMaterial> planMaterials = this.planMaterialMapper.selectByPlanIDAndTyp(masterPlanID, PlanTyp.Master);
        List<Integer> materialIds = planMaterials.stream().map(PlanMaterial::getMaterialId).collect(Collectors.toList());
        List<Material> materials = this.materialMapper.selectByIds(user.getToken(), materialIds);
        Map<Integer, Material> materialMap = ListUtilsKt.map(materials, Material::getId);

        materials.forEach(material -> {
            categoryIds.add(material.getCategoryId());
            categoryIds.add(material.getParentCategoryId());
        });


        List<Category> categories = this.categoryMapper.selectByIds(user.getToken(), categoryIds.stream().distinct().collect(Collectors.toList()));
        Map<String, Category> categoryMap = ListUtilsKt.map(categories, Category::getId);


        //物料
        MasterPlanCategory masterPlanCategory = this.masterPlanCategoryMapper.selectById(user.getToken(), masterPlan.getMasterPlanCategoryId());

        MasterPlanResponse masterPlanResponse = new MasterPlanResponse(masterPlan, projectMap.get(masterPlan.getProjectId()), masterPlanCategory, projectUserMap.get(masterPlan.getSubmitId()), projectUserMap.get(masterPlan.getCreatorId()));

        List<BatchPlanResponse> BatchPlanResponses = batchPlans.stream().map(batchPlan -> {
            return new BatchPlanResponse(batchPlan, projectMap.get(batchPlan.getProjectId()), categoryMap.get(batchPlan.getCategoryId()), projectUserMap.get(batchPlan.getSubmitId()), projectUserMap.get(batchPlan.getCreatorId()));
        }).collect(Collectors.toList());

        List<PlanMaterialResponse> planMaterialResponses = planMaterials.stream().map(planMaterial -> {
            Material material = materialMap.get(planMaterial.getMaterialId());
            MaterialResponse materialResponse = new MaterialResponse(material, categoryMap.get(material.getParentCategoryId()), categoryMap.get(material.getCategoryId()));
            return new PlanMaterialResponse(planMaterial, materialResponse, null);
        }).collect(Collectors.toList());

        return new MasterPlanDetailResponse(masterPlanResponse, BatchPlanResponses, planMaterialResponses);
    }


    //查看批次计划列表
    public PageInfo<BatchPlanResponse> batchPlanList(User user, String managementLevel, Integer projectId, String masterPlanNo, String batchPlanNo, String categoryName, PlanStatus status, Date submitStart, Date submitEnd, Date deadlineStart, Date deadlineEnd, Integer pageNum, Integer pageSize) {
        List<Project> projects = null;
        if (ObjectUtils.isEmpty(projectId)) {
            ArrayList<Integer> projectIds = new ArrayList<>();
            projectIds.add(projectId);

            projects = this.projectMapper.selectByIds(user.getToken(), projectIds);

        } else {
            projects = this.projectMapper.list(user.getToken(), "", managementLevel, user.getProjectIds());
        }

        if (projects == null || projects.isEmpty()) {
            return new PageInfo<>(Collections.emptyList());
        }


        List<Category> Categories = this.categoryMapper.findByName(user.getToken(), categoryName == null ? "" : categoryName);
        if (categoryName != null && !categoryName.isEmpty() && (Categories == null || Categories.isEmpty())) {
            return new PageInfo<>(Collections.emptyList());
        }


        PageHelper.startPage(pageNum, pageSize);
        //查找所有批次计划
        PageInfo<BatchPlan> batchPlans = new PageInfo<>(this.batchPlanMapper.selectBatchPlans(projects.stream().map(Project::getId).collect(Collectors.toList()), status, null, null, submitStart, submitEnd, deadlineStart, deadlineEnd, Categories.stream().map(Category::getId).collect(Collectors.toList()), masterPlanNo, batchPlanNo));


        Map<Integer, Project> projectMap = ListUtilsKt.map(projects, Project::getId);


        List<Integer> projectUserIds = batchPlans.getList().stream().flatMap(plan -> Stream.of(plan.getCreatorId(), plan.getSubmitId())).collect(Collectors.toList());
        List<ProjectUser> projectUsers = this.projectUserMapper.selectByIds(projectUserIds);
        Map<Integer, ProjectUser> projectUserMap = ListUtilsKt.map(projectUsers, ProjectUser::getId);


        Map<String, Category> categoryMap = ListUtilsKt.map(Categories, Category::getId);

        //查找所有总计划
        return batchPlans.convert(batchPlan -> new BatchPlanResponse(batchPlan, projectMap.get(batchPlan.getProjectId()), categoryMap.get(batchPlan.getCategoryId()), projectUserMap.get(batchPlan.getSubmitId()), projectUserMap.get(batchPlan.getCreatorId())));
    }


    public List<BatchPlanExportResponse> batchPlanExport(User user, String managementLevel, Integer projectId, String masterPlanNo, String batchPlanNo, String categoryName, PlanStatus status, Date submitStart, Date submitEnd, Date deadlineStart, Date deadlineEnd) {

        List<Project> projects = null;
        if (ObjectUtils.isEmpty(projectId)) {
            ArrayList<Integer> projectIds = new ArrayList<>();
            projectIds.add(projectId);

            projects = this.projectMapper.selectByIds(user.getToken(), projectIds);

        } else {
            projects = this.projectMapper.list(user.getToken(), "", managementLevel, user.getProjectIds());
        }

        List<Category> Categories = this.categoryMapper.findByName(user.getToken(), categoryName == null ? "" : categoryName);
        if (categoryName != null && !categoryName.isEmpty() && (Categories == null || Categories.isEmpty())) {
            return new ArrayList<>();
        }

        //查找所有批次计划

        List<BatchPlan> batchPlans = this.batchPlanMapper.selectBatchPlans(projects.stream().map(Project::getId).collect(Collectors.toList()), status, null, null, submitStart, submitEnd, deadlineStart, deadlineEnd, Categories.stream().map(Category::getId).collect(Collectors.toList()), masterPlanNo, batchPlanNo);


        Map<Integer, Project> projectMap = ListUtilsKt.map(projects, Project::getId);


        List<Integer> projectUserIds = batchPlans.stream().flatMap(plan -> Stream.of(plan.getCreatorId(), plan.getSubmitId())).collect(Collectors.toList());
        List<ProjectUser> projectUsers = this.projectUserMapper.selectByIds(projectUserIds);
        Map<Integer, ProjectUser> projectUserMap = ListUtilsKt.map(projectUsers, ProjectUser::getId);


        Map<String, Category> categoryMap = ListUtilsKt.map(Categories, Category::getId);


        //查找所有总计划
        return batchPlans.stream().map(batchPlan -> new BatchPlanExportResponse(batchPlan, projectMap.get(batchPlan.getProjectId()), categoryMap.get(batchPlan.getCategoryId()), projectUserMap.get(batchPlan.getSubmitId()))).collect(Collectors.toList());
    }

    //查看批次计划详情
    public BatchPlanDetailResponse batchPlanDetail(User user, int batchPlanID) {


        BatchPlan batchPlan = this.batchPlanMapper.selectByPrimaryKey(batchPlanID);
        List<Order> orders = this.orderMapper.selectByBatchPlanId(batchPlanID);

        Project project = this.projectMapper.selectById(user.getToken(), batchPlan.getProjectId());


        List<Integer> projectUserIds = orders.stream().map(Order::getCreatorId).collect(Collectors.toList());
        projectUserIds.add(batchPlan.getCreatorId());
        projectUserIds.add(batchPlan.getSubmitId());


        List<ProjectUser> projectUsers = this.projectUserMapper.selectByIds(projectUserIds.stream().distinct().collect(Collectors.toList()));
        Map<Integer, ProjectUser> projectUserMap = ListUtilsKt.map(projectUsers, ProjectUser::getId);


        List<PlanMaterial> planMaterials = this.planMaterialMapper.selectByPlanIDAndTyp(batchPlanID, PlanTyp.Batch);

        List<String> categoryIds = new ArrayList<>();
        categoryIds.add(batchPlan.getCategoryId());


        List<Integer> materialIds = planMaterials.stream().map(PlanMaterial::getMaterialId).collect(Collectors.toList());
        List<Material> materials = this.materialMapper.selectByIds(user.getToken(), materialIds);
        Map<Integer, Material> materialMap = ListUtilsKt.map(materials, Material::getId);

        materials.forEach(material -> {
            categoryIds.add(material.getCategoryId());
            categoryIds.add(material.getParentCategoryId());
        });

        orders.forEach(order -> {
            categoryIds.add(order.getCategoryId());
        });


        List<Category> categories = this.categoryMapper.selectByIds(user.getToken(), categoryIds.stream().distinct().collect(Collectors.toList()));
        Map<String, Category> categoryMap = ListUtilsKt.map(categories, Category::getId);


        BatchPlanResponse batchPlanResponse = new BatchPlanResponse(batchPlan, project, categoryMap.get(batchPlan.getCategoryId()), projectUserMap.get(batchPlan.getSubmitId()), projectUserMap.get(batchPlan.getCreatorId()));


        List<PlanMaterialResponse> planMaterialResponses = planMaterials.stream().map(planMaterial -> {
            Material material = materialMap.get(planMaterial.getMaterialId());
            MaterialResponse materialResponse = new MaterialResponse(material, categoryMap.get(material.getParentCategoryId()), categoryMap.get(material.getCategoryId()));
            return new PlanMaterialResponse(planMaterial, materialResponse, null);
        }).collect(Collectors.toList());


        List<Integer> supplierIds = orders.stream().map(Order::getSupplierId).collect(Collectors.toList());
        List<Supplier> suppliers = this.supplierMapper.selectByIds(user.getToken(), supplierIds);
        Map<Integer, Supplier> supplierMap = ListUtilsKt.map(suppliers, Supplier::getId);


        List<OrderResponse> orderResponses = orders.stream().map(order -> {
            return new OrderResponse(order, supplierMap.get(order.getSupplierId()), categoryMap.get(order.getCategoryId()), project, projectUserMap.get(order.getCreatorId()));
        }).collect(Collectors.toList());


        return new BatchPlanDetailResponse(batchPlanResponse, planMaterialResponses, orderResponses);
    }

    //查看订单列表
    public PageInfo<OrderResponse> orderList(
            DefaultUser defaultUser,
            String managementLevel,
            Integer projectId,
            String orderNo,
            String batchPlanNo,
            String categoryName,//物料大类
            String creatorName,
            OrderStatus status,
            Date submitStart,
            Date submitEnd,
            String searchKey,
            Integer pageNum,
            Integer pageSize
    ) {
        User user = defaultUser.getUser();


        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 20;
        }

        List<Project> projects = null;
        if (ObjectUtils.isEmpty(projectId)) {
            ArrayList<Integer> projectIds = new ArrayList<>();
            projectIds.add(projectId);

            projects = this.projectMapper.selectByIds(user.getToken(), projectIds);

        } else {
            projects = this.projectMapper.list(user.getToken(), "", managementLevel, user.getProjectIds());
        }


        if (projects == null || projects.isEmpty()) {
            return new PageInfo<>(Collections.emptyList());
        }

        if (defaultUser.isProjectConsumer() && searchKey != null && !searchKey.isEmpty()) {
            List<Project> newProjects = projects.stream().filter(project -> {
                return project.getName().contains(searchKey);
            }).collect(Collectors.toList());

            if (!newProjects.isEmpty()) {
                projects = newProjects;
            } else {
                return new PageInfo<>(new ArrayList<>());
            }
        }
        List<Category> Categories = this.categoryMapper.findByName(user.getToken(), categoryName == null ? "" : categoryName);
        if (categoryName != null && !categoryName.isEmpty() && (Categories == null || Categories.isEmpty())) {
            return new PageInfo<>(new ArrayList<>());
        }


        List<ProjectUser> projectUsers;
        List<Integer> creatorIds = null;
        if (creatorName != null && !creatorName.isEmpty()) {
            projectUsers = projectUserMapper.selectByName(creatorName);
            creatorIds = projectUsers.stream().map(ProjectUser::getId).collect(Collectors.toList());
            if (creatorIds.isEmpty()) {
                return new PageInfo<>();
            }
        } else {
            projectUsers = projectUserMapper.selectAll();
        }

        PageHelper.startPage(pageNum, pageSize);
        //查找所有批次计划
        PageInfo<Order> orders = new PageInfo<>(this.orderMapper.queryOrders(
                projects.stream().map(Project::getId).collect(Collectors.toList()),
                user.getSupplierIds(),
                orderNo, batchPlanNo,
                null,
                Categories.stream().map(Category::getId).collect(Collectors.toList()),
                creatorIds,
                status,
                submitStart,
                submitEnd,
                searchKey
        ));


        Map<Integer, Project> projectMap = ListUtilsKt.map(projects, Project::getId);

        List<Integer> supplierIds = orders.getList().stream().map(Order::getSupplierId).collect(Collectors.toList());
        List<Supplier> suppliers = this.supplierMapper.selectByIds(user.getToken(), supplierIds);
        Map<Integer, Supplier> supplierMap = ListUtilsKt.map(suppliers, Supplier::getId);


        Map<Integer, ProjectUser> projectUserMap = ListUtilsKt.map(projectUsers, ProjectUser::getId);


        Map<String, Category> categoryMap = ListUtilsKt.map(Categories, Category::getId);


        return orders.convert(order -> {
            return new OrderResponse(order, supplierMap.get(order.getSupplierId()), categoryMap.get(order.getCategoryId()), projectMap.get(order.getProjectId()), projectUserMap.get(order.getCreatorId()));
        });
    }


    public PageInfo<OrderResponse> orderByNo(User user, OrderStatus status, String no) {
        List<Order> orders = this.orderMapper.queryNo(status, no);
        if (orders == null || orders.isEmpty()) {
            return new PageInfo<>(new ArrayList<>());
        }

        List<Integer> projectIds = orders.stream().map(Order::getProjectId).distinct().collect(Collectors.toList());
        List<Project> projects = this.projectMapper.selectByIds(user.getToken(), projectIds);
        Map<Integer, Project> projectMap = ListUtilsKt.map(projects, Project::getId);

        List<Integer> supplierIds = orders.stream().map(Order::getSupplierId).collect(Collectors.toList());
        List<Supplier> suppliers = this.supplierMapper.selectByIds(user.getToken(), supplierIds);
        Map<Integer, Supplier> supplierMap = ListUtilsKt.map(suppliers, Supplier::getId);


        List<Integer> creatorIds = orders.stream().map(Order::getCreatorId).collect(Collectors.toList());
        List<ProjectUser> projectUsers = this.projectUserMapper.selectByIds(creatorIds);
        Map<Integer, ProjectUser> projectUserMap = ListUtilsKt.map(projectUsers, ProjectUser::getId);


        List<String> categoryIds = orders.stream().map(Order::getCategoryId).collect(Collectors.toList());
        List<Category> categories = this.categoryMapper.selectByIds(user.getToken(), categoryIds);
        Map<String, Category> categoryMap = ListUtilsKt.map(categories, Category::getId);


        return new PageInfo<>(orders.stream().map(order -> {
            return new OrderResponse(order, supplierMap.get(order.getSupplierId()), categoryMap.get(order.getCategoryId()), projectMap.get(order.getProjectId()), projectUserMap.get(order.getCreatorId()));
        }).collect(Collectors.toList()));
    }


    public List<OrderExportResponse> orderExport(User user, String managementLevel, Integer projectId, String orderNo, String batchPlanNo, String categoryName,//物料大类
                                                 String creatorName, OrderStatus status, Date submitStart, Date submitEnd) {


        List<Project> projects = null;
        if (ObjectUtils.isEmpty(projectId)) {
            ArrayList<Integer> projectIds = new ArrayList<>();
            projectIds.add(projectId);

            projects = this.projectMapper.selectByIds(user.getToken(), projectIds);

        } else {
            projects = this.projectMapper.list(user.getToken(), "", managementLevel, user.getProjectIds());
        }
        if (projects == null || projects.isEmpty()) {
            return new ArrayList<>();
        }


        List<Category> Categories = this.categoryMapper.findByName(user.getToken(), categoryName == null ? "" : categoryName);
        if (categoryName != null && !categoryName.isEmpty() && (Categories == null || Categories.isEmpty())) {
            return new ArrayList<>();
        }


        List<ProjectUser> projectUsers;
        List<Integer> creatorIds = null;
        if (creatorName != null && !creatorName.isEmpty()) {
            projectUsers = projectUserMapper.selectByName(creatorName);
            creatorIds = projectUsers.stream().map(ProjectUser::getId).collect(Collectors.toList());
        } else {
            projectUsers = projectUserMapper.selectAll();
        }

        //查找所有批次计划
        List<Order> orders = this.orderMapper.queryOrders(projects.stream().map(Project::getId).collect(Collectors.toList()), user.getSupplierIds(), orderNo, batchPlanNo, null, Categories.stream().map(Category::getId).collect(Collectors.toList()), creatorIds, status, submitStart, submitEnd, "");


        Map<Integer, Project> projectMap = ListUtilsKt.map(projects, Project::getId);

        Map<Integer, ProjectUser> projectUserMap = ListUtilsKt.map(projectUsers, ProjectUser::getId);


        Map<String, Category> categoryMap = ListUtilsKt.map(Categories, Category::getId);


        return orders.stream().map(order -> {
            return new OrderExportResponse(order, categoryMap.get(order.getCategoryId()), projectMap.get(order.getProjectId()), projectUserMap.get(order.getCreatorId()));
        }).collect(Collectors.toList());
    }

//查看订单详情


    public OrderDetailResponse orderDetail(User user, int orderId) {
        //查找订单
        Order order = this.orderMapper.selectByPrimaryKey(orderId);
        List<PlanMaterial> planMaterials = this.planMaterialMapper.selectByOrderID(orderId);
        List<Deliver> delivers = this.deliverMapper.selectByOrderId(orderId);
        Supplier supplier = this.supplierMapper.selectById(user.getToken(), order.getSupplierId());
        Project project = this.projectMapper.selectById(user.getToken(), order.getProjectId());

        ProjectUser creator = this.projectUserMapper.selectByPrimaryKey(order.getCreatorId());


        List<Integer> materialIds = planMaterials.stream().map(PlanMaterial::getMaterialId).collect(Collectors.toList());
        List<Material> materials = this.materialMapper.selectByIds(user.getToken(), materialIds);

        List<String> categoryIds = materials.stream().flatMap(material -> Stream.of(material.getCategoryId(), material.getParentCategoryId())).collect(Collectors.toList());
        categoryIds.add(order.getCategoryId());
        List<Category> categories = this.categoryMapper.selectByIds(user.getToken(), categoryIds.stream().distinct().collect(Collectors.toList()));
        Map<String, Category> categoryMap = ListUtilsKt.map(categories, Category::getId);


        Map<Integer, Material> materialMap = ListUtilsKt.map(materials, Material::getId);


        Category category = categoryMap.get(order.getCategoryId());

        OrderResponse orderResponse = new OrderResponse(order, supplier, category, project, creator);

        List<PlanMaterialResponse> planMaterialResponses = planMaterials.stream().map(planMaterial -> {
            Material material = materialMap.get(planMaterial.getMaterialId());
            MaterialResponse materialResponse = new MaterialResponse(material, categoryMap.get(material.getParentCategoryId()), categoryMap.get(material.getCategoryId()));
            return new PlanMaterialResponse(planMaterial, materialResponse, supplier);
        }).collect(Collectors.toList());


        List<Integer> supplierUserIds = delivers.stream().map(Deliver::getCreatorId).distinct().collect(Collectors.toList());
        List<SupplierUser> supplierUsers = supplierUserMapper.selectByIds(supplierUserIds);
        Map<Integer, SupplierUser> supplierUserMap = ListUtilsKt.map(supplierUsers, SupplierUser::getId);

        List<Integer> acceptanceIds = delivers.stream().map(Deliver::getAcceptanceId).collect(Collectors.toList());
        List<Acceptance> acceptances = acceptanceMapper.selectByIds(acceptanceIds);
        Map<Integer, Acceptance> acceptanceMap = ListUtilsKt.map(acceptances, Acceptance::getId);


        Map<Integer, ProjectUser> projectUserMap = new HashMap<>();
        List<Integer> acceptanceCreatorIds = acceptances.stream().map(Acceptance::getCreatorId).distinct().collect(Collectors.toList());
        if (acceptanceCreatorIds != null && !acceptanceCreatorIds.isEmpty()) {
            List<ProjectUser> projectUsers = projectUserMapper.selectByIds(acceptanceCreatorIds);
            projectUserMap = ListUtilsKt.map(projectUsers, ProjectUser::getId);
        }


        Map<Integer, ProjectUser> finalProjectUserMap = projectUserMap;
        List<DeliverResponse> subOrderResponseWithStatuses = delivers.stream().map(deliver -> {
            Acceptance acceptance = acceptanceMap.get(deliver.getAcceptanceId());
            ProjectUser acceptanceCreator = null;
            if (acceptance != null) {
                acceptanceCreator = finalProjectUserMap.get(acceptance.getCreatorId());
            }
            return new DeliverResponse(deliver, project, category, supplierUserMap.get(deliver.getCreatorId()), supplier, acceptance, acceptanceCreator);
        }).collect(Collectors.toList());


        return new OrderDetailResponse(orderResponse, planMaterialResponses, subOrderResponseWithStatuses);
    }


}
